#include "liblfcell.h"

void GenerateMaze(int X, int Y, int **maze)
{
	lfCell *Board;
	srand(std::time(0));
	Board = (lfCell*)( new lfCellMaze [X*Y]);

	for (int i=0;i<X*Y;++i) {
		Board[i].setStatus(!(rand()%2));
		int max=X*Y-1;
		int y=(int)(i/X);
		int x=i-y*X;
		int n=(y==0) ? (Y-1)*X+x : i-X;
		int e=(x==0) ? i+X-1 : i-1;
		int s=(y+1==Y) ? x : i+X;
		int w=(x+1==X) ? i+1-X : i+1;
		int ne=(x==0) ? n+X-1 : n-1;
		int se=(x==0) ? s+X-1 : s-1;
		int sw=(x+1==X) ? s+1-X : s+1;
		int nw=(x+1==X) ? n+1-X : n+1;
		Board[i].addNeighbor(&Board[n]);
		Board[i].addNeighbor(&Board[ne]);
		Board[i].addNeighbor(&Board[e]);
		Board[i].addNeighbor(&Board[se]);
		Board[i].addNeighbor(&Board[s]);
		Board[i].addNeighbor(&Board[sw]);
		Board[i].addNeighbor(&Board[w]);
		Board[i].addNeighbor(&Board[nw]);
	}

	for (int n=0;n<200;n++) {
		for (int i=0;i<X*Y;++i) {
			Board[i].updateSum();
		}

		for (int i=0;i<X*Y;++i) {
			Board[i].updateStatus();
		}
	}

	for (int i=0;i<X*Y;++i) {
		if (Board[i].checkStatus())
			maze[(int)(i/X)][i-((int)(i/X)*X)]=1;
		else
			maze[(int)(i/X)][i-((int)(i/X)*X)]=0;
	}

	delete [] Board;

	return;
}

bool  lfCell::m_Life() {
	return false;
}

bool  lfCell::m_Birth() {
	return false;
}

void  lfCell::updateSum() {
	f_Sum=0;

	for (std::vector<lfCell*>::iterator i=f_Neigh.begin();i != f_Neigh.end();++i) if ((*i)->checkStatus()) ++f_Sum;
};

void  lfCell::updateStatus() {
	if (f_Status)
		f_Status=m_Life();
	else
		f_Status=m_Birth();
}

bool  lfCell::checkStatus() {
	return f_Status;
}

void  lfCell::setStatus(bool status) {
	f_Status=status;
};

void  lfCell::addNeighbor(lfCell* cell) {
	f_Neigh.push_back(cell);
};

bool  lfCellMaze::m_Life() {
	if (lfCell::f_Sum!=1 && lfCell::f_Sum!=2 && lfCell::f_Sum!=3 && lfCell::f_Sum!=5) return false;

	return true;
};

bool  lfCellMaze::m_Birth() {
	if (lfCell::f_Sum==3) return true;

	return false;
};
